<?php
namespace addons\cloudstorage\driver;

use Qcloud\Cos\Client;
use think\File;
use think\Exception;

class Tencent extends Driver
{
    protected $cosClient;
    
    public function __construct($config, $domain = '')
    {
        parent::__construct($config, $domain);
        
        try {
            $this->cosClient = new Client([
                'region' => $this->config['region'],
                'schema' => 'https',
                'credentials' => [
                    'secretId'  => $this->config['secretId'],
                    'secretKey' => $this->config['secretKey']
                ]
            ]);
        } catch (Exception $e) {
            throw new Exception('腾讯云COS初始化失败: ' . $e->getMessage());
        }
    }
    
    /**
     * 上传文件
     */
    public function upload(File $file, $path = '')
    {
        try {
            $object = $this->getObjectPath($file, $path);
            $filePath = $file->getRealPath();
            
            $result = $this->cosClient->putObject([
                'Bucket' => $this->config['bucket'],
                'Key'    => $object,
                'Body'   => fopen($filePath, 'rb')
            ]);
            
            return [
                'status' => true,
                'path'   => $object,
                'url'    => $this->getUrl($object)
            ];
        } catch (Exception $e) {
            return [
                'status' => false,
                'msg'    => '上传失败: ' . $e->getMessage()
            ];
        }
    }
    
    /**
     * 删除文件
     */
    public function delete($filePath)
    {
        try {
            $this->cosClient->deleteObject([
                'Bucket' => $this->config['bucket'],
                'Key'    => $filePath
            ]);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }
    
    /**
     * 获取对象存储路径
     */
    protected function getObjectPath(File $file, $path = '')
    {
        $ext = $file->getExtension();
        $filename = md5(microtime(true) . uniqid()) . '.' . $ext;
        
        if ($path) {
            $path = rtrim($path, '/') . '/';
        }
        
        // 按日期组织路径
        $datePath = date('Ymd') . '/';
        
        return $path . $datePath . $filename;
    }
}
?>
